//
//  WBRefreshControl.m
//  王雷Sinoweibo
//
//  Created by wanglei on 16/11/30.
//  Copyright © 2016年 wanglei. All rights reserved.
//

#import "WBRefreshControl.h"

@implementation WBRefreshControl

- (void)setLastStatus:(WBRefrshStatue)lastStatus{
    
//    if (lastStatus == NULL) {
//        lastStatus = Normal;
//    }
    _lastStatus = lastStatus;
}

- (void)setStatus:(WBRefrshStatue)status{
    if (status == NULL) {
        status = Normal;
    }
//    注意这里要先给_status赋值,后面才可能取到值,才可能进行操作
    _status = status;
    switch (status) {
        case Normal:{
            self.tipLabel.text = @"下拉刷新";
            self.arrowIcon.hidden = false;
            //            小菊花停止转动
            [self.indicationView stopAnimating];
            [UIView animateWithDuration:0.25 animations:^{
            //              可以理解为位置的还原,每次赋值前都要这么做一次,理解为初始化也可以
                self.arrowIcon.transform = CGAffineTransformIdentity;
            }];
            
            if (self.lastStatus == Refreshing) {
                [UIView animateWithDuration:0.25 animations:^{
                    self.inset = self.scrollerview.contentInset;
            //      只有使用_inset才能取到CGfloat类型的top属性
                    _inset.top -= _RefreshHeight;
                    self.scrollerview.contentInset = _inset;
                }];
            }
        }
            break;
        case Pulling:{
            self.tipLabel.text = @"松开刷新";
            [UIView animateWithDuration:0.25 animations:^{
                self.arrowIcon.transform = CGAffineTransformMakeRotation(M_PI);
            }];
        }
            break;
        case Refreshing:
        {self.tipLabel.text = @"正在刷新";
//   发送通知,下面这个方法检测到UIControlEventValueChanged变化时会发送通知,此时HomeTableViewController中的load方法会被执行
            [self sendActionsForControlEvents:UIControlEventValueChanged];
//            隐藏箭头
            self.arrowIcon.hidden = true;
//            转动小菊花
            [self.indicationView startAnimating];
//            修改父视图的contentinset
            [UIView animateWithDuration:0.25 animations:^{
                self.inset = self.scrollerview.contentInset;
//                只有使用_inset才能取到CGfloat类型的top属性
                _inset.top += _RefreshHeight;
                self.scrollerview.contentInset = _inset;
            }];
            break;
        }
    }
//    储存状态
    self.lastStatus = _status;
}



-(instancetype)initWithFrame:(CGRect)frame{
//    初始值
    self.RefreshHeight = 60;
    CGRect rect = CGRectMake(0, -_RefreshHeight, ScreenWidth, _RefreshHeight);
    self = [super initWithFrame:rect];
    self.backgroundColor = [UIColor yellowColor];
    [self setupUi];
    return self;
}

- (void)endRefreshing{
//    延时执行
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 0.3*(NSEC_PER_SEC));
  dispatch_after(time, dispatch_get_main_queue(), ^{
      self.status = Normal;
  });
    
}

- (void)setupUi{
    UILabel *tipLabel = [UIlabel_extension factoryLabel:@"下拉刷新" fontsize:14 textColor:[UIColor darkGrayColor]];
    UIImageView *arrowIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"tableview_pull_refresh"]];
    UIActivityIndicatorView *indicationView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    UIImageView *backImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"refreshbg"]];
    
    self.tipLabel = tipLabel;
    self.arrowIcon = arrowIcon;
    self.indicationView = indicationView;
    self.backImageView = backImageView;
    
    [self addSubview:_tipLabel];
    [self addSubview:_arrowIcon];
    [self addSubview:_indicationView];
    [self addSubview:_backImageView];
    
    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX).offset(15);
        make.centerY.equalTo(self.mas_centerY);
    }];
    
    [_arrowIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_tipLabel.mas_left).offset(5);
        make.centerY.equalTo(_tipLabel.mas_centerY);
    }];
    
    [_indicationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(_arrowIcon);
    }];
    
    [_backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.bottom.equalTo(self);
    }];
}

//重写kvo观察者方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    /**
     *  当监控的某个属性的值改变了就会调用
     *  @param keyPath 属性名（哪个属性改了？）
     *  @param object  哪个对象的属性被改了？
     *  @param change  属性的修改情况（属性原来的值、属性最新的值）
     *  @param context void类型
     */
    CGFloat offSetY = self.scrollerview.contentOffset.y;
    CGFloat conaditionValue = -(_RefreshHeight + self.scrollerview.contentInset.top);
    
    NSLog(@"change = %@,offSetY = %f,conaditionValue = %f",change,offSetY,conaditionValue);
    
    //    结合http://www.jianshu.com/p/8440a3d181c9   和 http://www.jianshu.com/p/9091e5f34df5 再理解,其实直接打印出来看一下最直观
    
    if(self.scrollerview.dragging){
        //    需要先判断前面的状态,先将其卸载
        if((conaditionValue > offSetY) && (self.status == Normal)) {
            self.status = Pulling;
            NSLog(@"等待刷新状态");
        }
        if((conaditionValue < offSetY) && (self.status == Refreshing)){
            self.status = Normal;
            NSLog(@"正常状态");
        }
    }
    else {
        if (self.status == Pulling ) {
            //   只有从准备刷新的状态才能进入到正在刷新的状态
            self.status = Refreshing;
        }
    };
}


-(void)willMoveToSuperview:(UIView *)newSuperview{
    [super willMoveToSuperview:newSuperview];
    if ([newSuperview isKindOfClass:[UIScrollView class]] ) {
        self.scrollerview = newSuperview;
        /**
         *  注册一个监听
         *
         *  @param observer 观察者
         *  @param keyPath  属性名字
         *  @param options  属性的变化
         *  @param context  void类型
         */
        
        [_scrollerview addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    }
}


//移除观察者
- (void)dealloc{
    [self.scrollerview removeObserver:self forKeyPath:@"contentOffset"];
}


@end
